<template>
    <div class="header_main">
        <div class="editor_header">
            <div class="header-left">
                <div class="musicBox">
                    <span :class="['audio_cion', isLoading && 'loading']" @click="play">
                        <i :class="['iconfont', isLoading ? 'audioloading' : 'audioguangpanzhizuo']"></i>
                    </span>

                    <b>配音高清音质</b>
                </div>
                <span class="line"></span>
                <div class="musicBox" id="duoyinIcon" @click="duoyinDo">
                    <span class="audioTcon">
                        <i class="iconfont audioduoyinziicon"></i></span>
                    <b>拼音/多音字</b>
                </div>
                <div class="musicBox">
                    <span class="audioTcon" @click="numberDo">
                        <i class="iconfont audioshuzi"></i>
                    </span>
                    <b>数字连读</b>
                </div>
                <!-- @click="shdDo" -->
                <div class="musicBox">
                    <span class="audioTcon">
                        <i class="iconfont audiosheshidu"></i>
                    </span>
                    <b>摄氏度读法</b>
                </div>
                <span class="line"></span>
                <div class="audio">
                    <div class="audio_content">
                        <div class="avatar" @click="playDo">
                            <span class="atrCon ">
                                <i :class="['iconfont', person.avr]"></i>
                            </span>
                            <span class="mark">
                                <i :class="['iconfont', isPlay ? 'audiozanting1' : 'audiobofang']"></i>
                            </span>
                        </div>
                        <div class="audio_list">
                            <span class="title">{{ person.zh_name }}</span>
                            <p class="control">
                                <b style="margin-right: 10px;">{{ formatTime(starTime) }}</b>
                                <el-slider v-model="progress" @mouseleave="mouseleave" @mousedown="mousedown"
                                    @mouseup="mouseup" :min="0" :max="duration" :show-tooltip="false"
                                    @change="changeProgress" />
                                <b style="margin-left: 10px;">{{ formatTime(duration) }}</b>
                            </p>
                        </div>

                    </div>
                </div>
                <span class="line"></span>
            </div>

            <div class="header-right">
                <el-button :loading="loading" type="primary" @click="downFile('1')">下载音频</el-button>
            </div>
            <personContent></personContent>
        </div>
    </div>
</template>

<script>
import $ from "jquery";
import mixins from './mixins/mixins'
import { audioConvert, audioDownFile } from "@/api/audio"
import personContent from './personContent.vue';
export default {
    mixins: [mixins],
    data() {
        return {
            progress: 0,
            starTime: 0,
            src: '',
            duration: 0,
            audio: null,
            isLoading: false,
            loading: false,
            chinese: {
                0: '零',
                1: '一',
                2: '二',
                3: '三',
                4: '四',
                5: '五',
                6: '六',
                7: '七',
                8: '八',
                9: '九',
            }
        }
    },
    components: {
        personContent
    },
    computed: {
        strData() {
            return this.$store.getters.audioData
        },
        person() {
            return this.$store.getters.person
        },
        pos() {
            return this.$store.getters.pos
        },
        rate() {
            return this.$store.getters.rate
        },
        volume() {
            return this.$store.getters.volume
        },
        isPlay: {
            get: function () {
                return this.$store.getters.isPlay
            },
            set: function (val) {
                this.$store.dispatch('audio/setIsPlay', val)
            }

        }
    },

    methods: {
        changeProgress(val) {
            if (this.audio) {
                this.progress = val
                this.audio.currentTime = val
            }
        },
        mousedown(e) {
            if (this.audio) {
                if (e.target.className.includes('el-slider__button') || e.target.className == 'el-slider__runway' || e.target.className == 'el-slider__bar') {
                    this.audio.pause()
                }
            }
        },
        mouseup() {

            if (this.audio && this.isPlay) {
                this.audio.play()
            }

        },
        mouseleave() {
            if (this.audio && this.isPlay) {
                this.audio.play()
            }
        },
        // 格式化时间
        formatTime(time) {
            const minutes = Math.floor(time / 60)
            const seconds = Math.floor(time % 60)
            return `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`
        },
        reset() {
            this.progress = 0
            this.starTime = 0
            this.src = ''
            this.duration = 0
            this.audio = null
        },
        duoyinDo() {
            const selection = window.getSelection();
            if (selection.rangeCount) {
                const range = selection.getRangeAt(0);
                const text = range.toString();
                if (text.length == 1 && /^[\u4e00-\u9fa5]+$/.test(text)) {
                    const textNode = range.startContainer.parentElement;
                    const top = $(textNode).offset().top;
                    const left = $(textNode).offset().left;
                    console.log(left - $('.editer_conBox').offset().left);

                    const row = $(textNode).attr("row");
                    const col = $(textNode).attr("lang") - 1;
                    this.$store.dispatch('audio/setShowPoup', true)
                    this.$nextTick(() => {
                        $("#poup_main").css({
                            top: `${top - $('.editer_conBox').offset().top + 30}px`,
                            left: `${left - $('.editer_conBox').offset().left - $("#poup_main").width() / 2}px`,
                        });
                    });
                    const duoyinList = {
                        col,
                        row,
                        duoyin: this.strData[row][col].duoyin,
                    };
                    $(document).on('click', (event) => {
                        if (!$(event.target).closest('#poup_main').length && !$(event.target).closest('#duoyinIcon').length) {
                            this.$store.dispatch('audio/setShowPoup', false)
                            this.$store.dispatch('audio/setDuoyinList', [])
                        }
                    });
                    this.$store.dispatch('audio/setDuoyinList', duoyinList)
                } else {
                    this.$message({
                        message: '请滑动选择单个中文',
                        type: 'warning',
                    })
                }
            }
        },
        play() {
            if (this.strData[0].length) {
                if (!this.isPlay) {
                    this.reset()
                    this.isLoading = true
                    const arr = [];
                    this.strData.forEach((item, i) => {
                        if (i > 0) {
                            arr.push({
                                text: '       '
                            })
                        }
                        item.forEach((p) => {
                            if (p.isDuo) {
                                arr.push({
                                    text: p.isDuo,
                                });
                            } else if (p.isnum) {
                                arr.push({
                                    text: this.chinese[p.text],
                                });
                            } else {
                                arr.push({
                                    text: p.text,
                                });
                            }

                        });
                    });
                    this.textarea1 = arr.map((item) => item.text).join("")
                    this.textAudio()
                } else {
                    this.$message({
                        message: '当前配音正在播放中',
                        type: 'warning',
                    })
                }

            } else {
                this.$message({
                    message: '请输入您要配音的内容',
                    type: 'warning',
                })
            }

        },
        async textAudio() {
            let params = {
                text: this.textarea1,
                voice: this.person.name,
                rate: this.rateDo(this.rate), //语速
                volume: this.volumeDo(this.volume),
            }
            let data = await audioConvert(params);
            this.isLoading = false
            if (data.code == "000000") {
                this.fileId = data.fileId;
                this.downFile("0");
            }
        },
        rateDo(rate) {
            const result = parseFloat((rate - 1.1).toFixed(2))
            if (result < 0) {
                return `${result * 100}%`

            } else if (result > 0) {
                return `+${result * 100}%`

            } else {
                return `+${result}%`
            }
        },
        volumeDo(volume) {
            const result = volume - 10
            if (result < 0) {
                return `${result * 10}%`

            } else if (result > 0) {
                return `+${result * 100}%`

            } else {
                return `+${result}%`
            }
        },
        async downFile(type) {
            if (this.fileId) {
                if (type == 1) {
                    this.loading = true
                }
                let params = {
                    fileId: this.fileId,
                }
                let data = await audioDownFile(params);
                this.loading = false
                let blob = new Blob([data], { type: "audio/mpeg" });
                const url = URL.createObjectURL(blob);
                const a = document.createElement("a");
                switch (type) {
                    case "0":
                        this.src = url;
                        this.audioPlay()
                        break;
                    case "1":
                        a.href = url;
                        a.download = this.fileId;
                        a.click();
                        a.remove();
                        break;
                }
            } else {
                this.$message({
                    message: '请点击右上角按钮制作配音',
                    type: 'warning',
                })
            }

        },
        audioPlay() {
            this.audio = new Audio(this.src);
            let that = this
            this.audio.addEventListener('loadedmetadata', function () {
                that.duration = this.duration
            })
            this.audio.addEventListener('timeupdate', () => {
                this.starTime = this.audio.currentTime
                this.progress = this.audio.currentTime
            })
            this.audio.addEventListener('ended', () => {
                this.starTime = 0
                this.progress = 0
                this.isPlay = false
            })
            this.isPlay = true
            this.audio.play()
        },
        playDo() {
            if (this.audio) {
                this.isPlay = !this.isPlay
                if (this.isPlay) {
                    this.audio.play()
                } else {
                    this.audio.pause()
                }
            } else {
                this.$message({
                    message: '请点击右上角按钮制作配音',
                    type: 'warning',
                })
            }

        },
        numberDo() {
            const selection = window.getSelection();
            if (selection.rangeCount) {
                const range = selection.getRangeAt(0);
                const text = range.toString();
                if (text) {
                    const num = text.replace(/\s+/g, "") * 1;
                    if (/^[0-9]*$/.test(num)) {

                        const n = this.pos.col - num.toString().length;
                        this.strData[this.pos.row].forEach((item, i) => {
                            if (i >= n) {
                                if (/^[0-9]*$/.test(item.text) && i < this.pos.col) {
                                    item.isnum = true;
                                }
                            }
                        });
                        this.setContent();
                    } else {
                        this.$message({
                            message: '请滑动选择数字内容',
                            type: 'warning',
                        })
                    }
                } else {
                    this.$message({
                        message: '请滑动选择内容',
                        type: 'warning',
                    })
                }

            }
        },
        shdDo() {
            const selection = window.getSelection();
            if (selection.rangeCount) {
                const range = selection.getRangeAt(0);
                const text = range.toString();
                if (text) {
                    const num = text.replace(/\s+/g, "") * 1;
                    if (/^[0-9]*$/.test(num)) {

                        const n = this.pos.col - num.toString().length;
                        this.strData[this.pos.row].forEach((item, i) => {
                            if (i >= n) {
                                if (/^[0-9]*$/.test(item.text) && i < this.pos.col) {
                                    item.isShd = true;
                                }
                            }
                        });
                        this.setContent();
                    } else {
                        this.$message({
                            message: '请滑动选择数字内容',
                            type: 'warning',
                        })
                    }
                } else {
                    this.$message({
                        message: '请滑动选择内容',
                        type: 'warning',
                    })
                }

            }
        },
    }
}
</script>

<style lang="less">
.header_main {
    background: #f4f6f7;

    .editor_header {
        width: 1200px;
        padding: 5px 20px;
        margin: auto;
        display: flex;
        flex-wrap: nowrap;
        justify-content: space-between;
        box-sizing: border-box;
        position: relative;
        border-top: 1px solid #e5e5e5;
        border-bottom: 1px solid #e5e5e5;
        user-select: none;
        z-index: 999;

        .header-left {
            display: flex;

            .musicBox {
                width: 100px;
                height: 100%;
                height: 66px;

                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                cursor: pointer;

                &:hover {
                    background-color: #eee;
                }

                .audio_cion {
                    display: block;
                    width: 30px;
                    width: 30px;
                    text-align: center;
                    line-height: 30px;

                    background-repeat: no-repeat;
                    background-size: contain;
                    background-position: center;
                    cursor: pointer;
                    transition: all 0.5s;

                    &:hover {
                        transform: scale(1.1);
                    }

                    i {
                        font-size: 26px;
                        color: #1296db
                    }
                }


                .audioTcon {
                    display: block;
                    width: 30px;
                    height: 30px;
                    text-align: center;
                    line-height: 30px;
                    background-repeat: no-repeat;
                    background-size: contain;
                    background-position: center;
                    cursor: pointer;

                    i {
                        font-size: 26px;
                        color: #515151;
                    }
                }


                .loading {
                    animation: loading 0.3s linear infinite;
                    // border: 2px solid #1296db;
                    border-radius: 50%;
                }

                @keyframes loading {
                    0% {
                        transform: rotate(0deg);
                    }

                    // 50% {
                    //     transform: rotate(180deg);
                    // }

                    100% {
                        transform: rotate(360deg);
                    }
                }


                b {
                    font-style: normal;
                    font-size: 13px;
                    font-weight: 400;
                    color: #6f6f6f;
                    margin-top: 4px;
                }
            }

            .line {
                width: 2px;
                height: 100%;
                background-color: #ccc;
                margin: 0 10px;
                font-size: 14px;
            }
        }

        .audio {
            width: 600px;
            height: 100%;
            display: flex;
            padding: 10px;
            box-sizing: border-box;
            box-sizing: border-box;
            align-items: center;

            .audio_content {
                width: 100%;
                display: flex;
                align-items: center;

                .avatar {
                    width: 50px;
                    height: 50px;
                    position: relative;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    border-radius: 50%;
                    border: 1px solid #bec7d4;
                    overflow: hidden;
                    background-color: rgba(6, 124, 167, .4);
                    cursor: pointer;

                    .atrCon {
                        display: block;
                        width: 80%;
                        height: 80%;
                        background-size: contain;
                        background-position: center;
                        background-repeat: no-repeat;
                        display: flex;
                        justify-content: center;
                        align-items: center;

                        i {
                            font-size: 38px;
                        }

                    }



                    .mark {
                        position: absolute;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background-color: rgba(0, 0, 0, 0.4);
                        border-radius: 50%;
                        color: #eee;
                        display: flex;
                        align-items: center;
                        justify-content: center;

                    }


                }

                .audio_list {
                    width: 90%;

                    margin: auto;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;

                    .el-slider__button {
                        width: 16px;
                        height: 16px;
                    }

                    .title {
                        display: block;
                        font-size: 15px;
                        margin-left: 4px;
                        margin-top: 5px;

                    }

                    .control {
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                        padding: 0;
                        margin: 0;

                        b {
                            font-weight: 400;
                            font-size: 14px;
                            margin: 0 5px;

                        }
                    }
                }
            }
        }

        .header-right {
            display: flex;
            align-items: center;

            .down_btn {
                background-color: #3583fb;
                color: #fff;
                border: none;
                width: 100px;
                height: 40px;
                border-radius: 4px;
                cursor: pointer;
            }
        }
    }
}
</style>